package com.xiaoyuzhou;

import java.util.Map;

import com.xiaoyuzhou.R;
import com.xiaoyuzhou.logic.DataService;
import com.xiaoyuzhou.untity.AddressData;
import com.xiaoyuzhou.untity.WeatherHeap;
import com.xiaoyuzhou.utils.NetUtils;
import com.xiaoyuzhou.utils.SPUtils;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class WidgetService extends Service{
	
	public static Context mContext;
	public static final int MESSAGE_REFRESH_WEATHER = 2;
	
	/**
	 * 用来更新时间和发送天气请求
	 */
	BroadcastReceiver mBroadcast = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_TIME_TICK)) {
				mContext.sendBroadcast(new Intent(MyWidgetProvider.ACTION_TIME_TICK));
			}
			if(action.equals(NetWorkReceiver.ACTION_REQUEST_WEATHER)) {
				boolean checkLastUpdate = intent.getBooleanExtra(DataService.CHECKLASTUPDATE, true);
				requestData(checkLastUpdate);
			}
		}
	};
	
	@Override
	public void onCreate() {
		super.onCreate();
		mContext = this;
	}
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			//刷新天气信息
			case MESSAGE_REFRESH_WEATHER:
				Intent i1 = new Intent(MyWidgetProvider.ACTION_WIDGET_UPDATE_WEATHER);
				WeatherHeap weather = (WeatherHeap)msg.obj;
				i1.putExtra(DataService.WEATHER_DETAIL, weather.getForecast().get(0).getWeatherDetail());	
				i1.putExtra(DataService.TEMPERATURE, weather.getCurrentTemperature());
				i1.putExtra(DataService.WIND, weather.getCurrentWind());
				i1.putExtra(DataService.LOCATION, weather.getLocation());
				mContext.sendBroadcast(i1);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println("start service");
		//ACTION_TIME_TICK必须动态添加，写在清单文件中无效
		mContext.registerReceiver(mBroadcast, new IntentFilter(Intent.ACTION_TIME_TICK));
		mContext.registerReceiver(mBroadcast, new IntentFilter(NetWorkReceiver.ACTION_REQUEST_WEATHER));
		//请求定位和天气的数据
		requestData(true);
		return super.onStartCommand(intent, flags, startId);
	}
	
	/**
	 * 先请求位置数据、再请求天气数据
	 * Description:
	 * @param ignoreCheck 是否检测上次更新时间，默认检测
	 *<br/> ModifiedLog:
	 *<br/> Log ID: 1.0 (Log编号 依次递增)
	 * <br/>Modified By: liubin Email:liubin@d-heaven.com at 2012-12-28 上午10:06:05
	 */
	public void requestData(final boolean checkLastUpdate) {
		//检测网络是否连接
		if(!NetUtils.checkNet(mContext)) {
			Toast.makeText(mContext, mContext.getText(R.string.net_error), Toast.LENGTH_SHORT).show();
			return;
		}
		//定位获取经纬度
		final LocationManager	locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
		String provider = findBestProvider(locationManager);
		locationManager.requestLocationUpdates(provider, 5000, 5000, new LocationListener(){
			@Override
			public void onLocationChanged(Location location) {
				double lat = location.getLatitude();
				double lng = location.getLongitude();
				System.out.println("lat: " + lat);
				System.out.println("lng: " + lng);
				//异步处理网络请求
				(new GetDataThread(lat, lng, checkLastUpdate)).start();
				locationManager.removeUpdates(this);
			}
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {}
			@Override
			public void onProviderEnabled(String provider) {}
			@Override
			public void onProviderDisabled(String provider) {}
		});
	}
	
	/**
	 * 获取信息的线程，主要获取城市和天气信息
	 * @version 1.0
	 * @author liubin Email:liubin@d-heaven.com
	 * @Date 2012-11-2 下午12:18:22 created.
	 */
	private class GetDataThread extends Thread {
		double lat,lng;
		boolean checkLastUpdate = true;//是否需要检测上次更新时间
		public GetDataThread(double lat, double lng, boolean checkLastUpdate) {
			this.lat = lat;
			this.lng = lng;
			this.checkLastUpdate = checkLastUpdate;
		}
		@Override
		public void run() {
			//先请求位置信息
			AddressData address = DataService.getAddressByLocate(lat, lng);
			if(address != null) {
				//不需要北京市的 市 字
				String city = address.getCity().replace("市", "");
				//请求天气信息的时候不需要海淀区的 区 字
				String district = address.getDistrict().replace("区", "");
				if(city != null && !city.equals("") && district != null && !district.equals("")) {
					String location = city + "-" + address.getDistrict();
					//判断是否需要更新天气
					boolean ifUpdate = true;
					if(checkLastUpdate) {//如果需要检测上次更新时间
						ifUpdate = DataService.should_updateWeather(mContext, location);
					}
					if(ifUpdate) {
						System.out.println("now will update data");
						//保存当前定位的城市
						SPUtils.saveData(mContext, DataService.SP_NAME_LASTUPDATE, DataService.LOCATION, location);
						//再根据定位得到的城市来请求天气信息
						//先去数据库中找对应的城市编码
						String cityCode = DataService.getCityCodeFromSP(mContext, district, city);
						//没有数据，请求网络下载新数据
						if(cityCode == null || cityCode.equals("")) {
							String regionCode = DataService.province.get(address.getProvince().replace("省", "").replace("市", ""));
							System.out.println("regionCode:"+regionCode);
							Map<String, String> cities = DataService.getSupportCity(regionCode);
							if(DataService.saveSupportCity(mContext, cities)) {
								//下载保存完毕，再取一次
								cityCode = DataService.getCityCodeFromSP(mContext, district, city);
							}
						}
						System.out.println("cityCode:" + cityCode);
						WeatherHeap weatherHeap = DataService.getWeather(cityCode);
						weatherHeap.setLocation(location);
						if(weatherHeap != null) {
							//保存天气预报至files目录
							DataService.saveForecast2Data(mContext, weatherHeap);
							//天气已更新，刷新上次更新时间为当前
							SPUtils.saveData(mContext, DataService.SP_NAME_LASTUPDATE
									, DataService.UPDATE_TIME,  System.currentTimeMillis()+"");
							Message msg1 = mHandler.obtainMessage();
							msg1.what = MESSAGE_REFRESH_WEATHER;
							msg1.obj = weatherHeap;
							mHandler.sendMessage(msg1);
						}
					}
				} 				
			}
		}
	}
	
	/**
	 * 获取最好的提供者
	 * @param context
	 * @return
	 */
	private String findBestProvider(LocationManager locationManager) {
		String provider = LocationManager.NETWORK_PROVIDER;
		//依次判断两个定位是否可用，取可用中的最好的那一个
//		if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
//			provider = LocationManager.GPS_PROVIDER;
//		} else if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
//			provider = LocationManager.NETWORK_PROVIDER;
//		} 
		return provider;
	}
	
	@Override
	public void onDestroy() {
		mContext.unregisterReceiver(mBroadcast);
		super.onDestroy();
	}
	
}
